import styles from './index.less';
import React from 'react';
import {Group, Layer, Stage, Text, Transformer} from 'react-konva';

/**
 * 参考
 * 绘制canvas文本光标，实现双击编辑效果
 * @returns
 */
export default function IndexPage() {

  let textNode, tr, layer, stage, group;

  const onDblClick = (e) => {
    // hide text node and transformer:
    textNode.hide();
    tr.hide();
    layer.draw();

    // create textarea over canvas with absolute position
    // first we need to find position for textarea
    // how to find it?

    // at first lets find position of text node relative to the stage:
    var textPosition = textNode.absolutePosition();

    // then lets find position of stage container on the page:
    var stageBox = stage.container().getBoundingClientRect();

    // so position of textarea will be the sum of positions above:
    var areaPosition = {
      x: stageBox.left + textPosition.x,
      y: stageBox.top + textPosition.y
    };

    // create textarea and style it
    var textarea = document.createElement('textarea');
    document.body.appendChild(textarea);

    // apply many styles to match text on canvas as close as possible
    // remember that text rendering on canvas and on the textarea can be different
    // and sometimes it is hard to make it 100% the same. But we will try...
    textarea.value = textNode.text();
    textarea.style.position = 'absolute';
    textarea.style.top = areaPosition.y + 'px';
    textarea.style.left = areaPosition.x + 'px';
    textarea.style.width = textNode.width() - textNode.padding() * 2 + 'px';
    textarea.style.height =
      textNode.height() - textNode.padding() * 2 + 5 + 'px';
    textarea.style.fontSize = textNode.fontSize() + 'px';
    textarea.style.border = 'none';
    textarea.style.padding = '0px';
    textarea.style.margin = '0px';
    textarea.style.overflow = 'hidden';
    textarea.style.background = 'none';
    textarea.style.outline = 'none';
    textarea.style.resize = 'none';
    textarea.style.lineHeight = textNode.lineHeight();
    textarea.style.fontFamily = textNode.fontFamily();
    textarea.style.transformOrigin = 'left top';
    textarea.style.textAlign = textNode.align();
    textarea.style.color = textNode.fill();
    let rotation = textNode.rotation();
    var transform = '';
    if (rotation) {
      transform += 'rotateZ(' + rotation + 'deg)';
    }

    var px = 0;
    // also we need to slightly move textarea on firefox
    // because it jumps a bit
    var isFirefox =
      navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
    if (isFirefox) {
      px += 2 + Math.round(textNode.fontSize() / 20);
    }
    transform += 'translateY(-' + px + 'px)';

    textarea.style.transform = transform;

    // reset height
    textarea.style.height = 'auto';
    // after browsers resized it we can set actual value
    textarea.style.height = textarea.scrollHeight + 3 + 'px';

    textarea.focus();

    function removeTextarea() {
      textarea.parentNode.removeChild(textarea);
      window.removeEventListener('click', handleOutsideClick);
      textNode.show();
      tr.show();
      tr.forceUpdate();
      layer.draw();
    }

    function setTextareaWidth(newWidth) {
      if (!newWidth) {
        // set width for placeholder
        newWidth = textNode.placeholder.length * textNode.fontSize();
      }
      // some extra fixes on different browsers
      var isSafari = /^((?!chrome|android).)*safari/i.test(
        navigator.userAgent
      );
      var isFirefox =
        navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
      if (isSafari || isFirefox) {
        newWidth = Math.ceil(newWidth);
      }

      var isEdge =
        document.documentMode || /Edge/.test(navigator.userAgent);
      if (isEdge) {
        newWidth += 1;
      }
      textarea.style.width = newWidth + 'px';
    }

    textarea.addEventListener('keydown', function (e) {
      // hide on enter
      // but don't hide on shift + enter
      if (e.keyCode === 13 && !e.shiftKey) {
        textNode.text(textarea.value);
        removeTextarea();
      }
      // on esc do not set value back to node
      if (e.keyCode === 27) {
        removeTextarea();
      }
    });


    textarea.addEventListener('keydown', function (e) {
      const scale = textNode.getAbsoluteScale().x;
      setTextareaWidth(textNode.width() * scale);
      textarea.style.height = 'auto';
      textarea.style.height =
        textarea.scrollHeight + textNode.fontSize() + 'px';
    });

    function handleOutsideClick(e) {
      if (e.target !== textarea) {
        textNode.text(textarea.value);
        removeTextarea();
      }
    }

    setTimeout(() => {
      window.addEventListener('click', handleOutsideClick);
    });
  }

  const trRef = React.useRef(null);
  const textRef = React.useRef(null);
  const layerRef = React.useRef(null);
  const stageRef = React.useRef(null);
  const groupRef = React.useRef(null);
  const MIN_WIDTH = 100;

  const [selection, setSelection] = React.useState(null)

  React.useEffect(() => {
    trRef.current?.nodes([textRef.current]);
    textNode = textRef.current
    tr = trRef.current
    layer = layerRef.current
    stage = stageRef.current
    group = groupRef.current

    document.addEventListener('select', (e) => {
      console.log(e.target.selectionStart);
      console.log(e.target.selectionEnd);
      console.log(e.target);
    });
  }, [])

  return (
    <div style={styles.body}>
      <div>{textRef.current?.width()}</div>
      <div>{textRef.current?.scaleX()}</div>
      <div>
        <button onClick={e => {


        }}>变绿
        </button>
      </div>
      <Stage ref={stageRef} width={window.innerWidth} height={window.innerHeight}>
        <Layer ref={layerRef}>
          <Group ref={groupRef}>
            <Text
              ref={textRef}
              x={50}
              y={80}
              fontSize={20}
              draggable={true}
              onDragMove={e => {
              }}
              onDblClick={onDblClick}
              width={200}
              scaleX={1}
              scaleY={1}
              text={'Hello from the Konva framework. Try to resize me.'}
              onTransform={() => {
                textRef.current.setAttrs({
                  width: Math.max(textRef.current.width() * textRef.current.scaleX(), MIN_WIDTH),
                  scaleX: 1,
                  scaleY: 1,
                })
              }}/>
            <Transformer
              ref={trRef}
              padding={5}
              enabledAnchors={['middle-left', 'middle-right']}
              boundBoxFunc={(oldBox, newBox) => {
                if (newBox.width < MIN_WIDTH) {
                  return oldBox;
                }
                return newBox;
              }}/></Group>
        </Layer>
      </Stage>
    </div>
  );
}
